package com.liliudong.cursormate.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.hutool.http.HttpStatus;
import com.liliudong.cursormate.common.R;
import com.liliudong.cursormate.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * GlobleExceptionHandler
 *
 * @author liliudong
 * @version 1.0
 * @description
 * @date 2023/7/26 18:55
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    private static final String UNKNOWN_ERR = "未知异常";
    private static final String LOGIN_FAIL = "登录失效";
    private static final String FORBIDDEN = "权限不足";

    /**
     * 异常
     *
     * @param exception 异常
     * @return {@link R}<{@link ?}>
     */
    @ExceptionHandler(Exception.class)
    public R<?> exception(Exception exception) {
        log.error(exception.getMessage(), exception);
        return R.error(UNKNOWN_ERR);
    }

    /**
     * 异常
     *
     * @param exception 异常
     * @return {@link R}<{@link ?}>
     */
    @ExceptionHandler(BusinessException.class)
    public R<?> exception(BusinessException exception) {
        log.error(exception.getMessage(), exception);
        return R.error(exception.getCode(), exception.getMessage());
    }

    /**
     * 异常
     *
     * @param exception 例外
     * @return {@link R}<{@link ?}>
     */
    @ExceptionHandler(NotLoginException.class)
    public R<?> exception(NotLoginException exception) {
        log.error(exception.getMessage(), exception);
        return R.error(HttpStatus.HTTP_UNAUTHORIZED, LOGIN_FAIL);
    }

    /**
     * 权限不足
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(NotPermissionException.class)
    public R<?> exception(NotPermissionException exception) {
        log.error(exception.getMessage(), exception);
        return R.error(HttpStatus.HTTP_FORBIDDEN, FORBIDDEN);
    }


}
